<template>
  <el-dialog :title="info.title" :visible.sync="visible" center width="320px" :before-close="handleCancel">
    <el-tree
      ref="appTree"
      class="fs20"
      show-checkbox
      default-expand-all
      node-key="id"
      check-strictly
      :props="defaultProps"
      :default-checked-keys="checkedKeys"
      :data="organs"
    />
    <el-row>
      <el-col :span="24">
        <div class="fr mt10">
          <el-button size="small" @click="handleCancel()">取 消</el-button>
          <el-button type="primary" size="small" @click="handleEdit()">保 存</el-button>
        </div>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { queryOrganRoot } from '@/api/organ'
import { queryPowers, editPower } from '@/api/disk'
import form from '@/utils/form'

export default {
  extends: form,
  data() {
    return {
      checkedKeys: null,
      organs: null,
      defaultProps: {label: 'name'}
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.$set(this, 'form', this.info.edit)
        this.queryOrganRoot()
        this.queryPowers()
      }
    },
    getData: {
      type: Function,
      default: function() {}
    }
  },
  mounted() {
  },
  methods: {
    queryOrganRoot() {
      queryOrganRoot().then(response => {
        this.organs = response.organs
      }).catch(error => {
        this.$message.error(error.msg ? error.msg : '操作失败')
      })
    },
    queryPowers() {
      queryPowers({su_id: this.form.su_id}).then(response => {
        let checkedKeys = []
        response.list.forEach(v => {
          checkedKeys.push(v.dept_id)
        })
        this.$set(this, 'checkedKeys', checkedKeys)
      }).catch(error => {
        this.$message.error(error.msg ? error.msg : '操作失败')
      })
    },
    handleEdit() {
      var v = this.$refs['appTree'].getCheckedKeys()
      if (v.length == 0) {
        this.$message({ message: '请勾选权限', type: 'warning' })
        return
      }
      editPower({
        'ids': v.join(','),
        'su_id': this.form.su_id
      }).then(response => {
        this.getData()
        this.handleCancel()
        this.$message.success('编辑成功')
      })
    },
    handleCancel(done) {
      if (this.$refs['appTree']) this.$refs['appTree'].setCheckedKeys([])
      if (done && typeof done === Function) {
        done()
      } else {
        this.visible = false
      }
    }
  }
}
</script>

<style>

</style>
